import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';

import 'package:smart_translator/app/const/AppConst.dart';
import 'package:smart_translator/app/db/DbDAOHelper.dart';
import 'package:smart_translator/app/event/DataCallBack.dart';
import 'package:smart_translator/app/utils/CommonUtil.dart';
import 'package:smart_translator/app/widgets/CommonWidgets.dart';
import '../../db/database.dart';
import '../../nets/NetWorkManager.dart';
import '../../routes/app_pages.dart';
import '../../services/AudioService.dart';
import 'package:web_socket_client/web_socket_client.dart' as ws;

import '../../style/app_colors.dart';


class IndexViewController extends GetxController {

  var offlineMode = false.obs;
  var onlyShowscript = false.obs;
  var allowOtherAppInput = false.obs;
  var autoPronounce = false.obs;


  var singleScrollController = ScrollController().obs;

  var voiceType = 1.obs;
  var voidSpeed = 10.obs;

  var autoSpeakWbSocket;
  Timer? ttsWsTimer;

  Uint8List audioData =  Uint8List(0);

  AudioService audioService = Get.find<AudioService>();


  // 防抖计时器
  Timer? _debounceTimer;
  // 是否处于冷却状态
  bool _isCoolingDown = false;

  AudioPlayer? player;

  @override
  void onInit() {
    super.onInit();
    freshSettingState();
  }

  void initWsAndRecorder() {
    audioService.initAllState();
    audioService.isAtIndexPage = true;
    audioService.connectedWsAndRecorder('wss://${NetWorkManager.WS_IP + NetWorkManager.SPEECH_RECOGNITION}?channel=azure&transStrategy=2', DataCallBack(
        confirmCallBack: (v) {

        },
        businessCallBack: (v) {
         /* if (allowOtherAppInput.value) {
            Clipboard.setData(ClipboardData(text: audioService.indexPageFinalToLanguage.value));
          }*/

          // 延迟到下一帧执行，确保布局完成
          SchedulerBinding.instance.addPostFrameCallback((_) {
            _autoScrollToBottom();
          });
        },
        deviceCallBack: (m) {
           audioService.record();
        }
    ));
  }

  @override
  void onReady() {
    super.onReady();

    // initTTsWbSocket();
  }

  @override
  void onClose() {
    super.onClose();
    if (ttsWsTimer != null) {
      ttsWsTimer!.cancel();
    }
    audioService.stopRecorder();
    _debounceTimer?.cancel(); // 组件销毁时取消计时器
  }



  void freshSettingState() async {
     Setting? setting =   await DbDAOHelper().obtainIndexSettings();
     if (setting == null) {
        offlineMode.value = false;
        onlyShowscript.value = false;
        allowOtherAppInput.value = true;
        autoPronounce.value = true;

        voidSpeed.value = 10;
        voiceType.value = 1;

     } else {
       offlineMode.value = setting.off_line;
       onlyShowscript.value = setting.only_show_trans_text;
       allowOtherAppInput.value = setting.allowOtherInput;
       autoPronounce.value = setting.auto_play;

       voidSpeed.value = setting.speechSpeed;
       voiceType.value = setting.voiceType;
     }
  }


  void updateSettingData() async {
   DbDAOHelper().saveOrUpdateIndexSetting(offlineMode.value, onlyShowscript.value,
       allowOtherAppInput.value, autoPronounce.value, voiceType.value, voidSpeed.value);
  }


  void _autoScrollToBottom() {
    // 使用 animateTo 实现平滑滚动
    singleScrollController.value.animateTo(
      singleScrollController.value.position.maxScrollExtent,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOut,
    );
  }

  void goToScriptInputPage() {
    if (audioService.isPlaying.value) {
      audioService.stopRecorderForIndex();
    }
    stopAudioPlay();

    Get.toNamed(Routes.INDEX_TRANSLATION);
  }


  void goToScriptInputPage2() {
    if(audioService.indexPageFinalToLanguage.value.trim() == '') {
       return;
    }

    if (audioService.isPlaying.value) {
      audioService.stopRecorderForIndex();
    }
    stopAudioPlay();

    Get.toNamed(Routes.INDEX_TRANSLATION);
  }


  void saveTranslationRecords() {
    if (audioService.indexPageFinalToLanguage.value.trim() != '' && audioService.indexPageFinalToLanguage.value.trim() != '') {
      DbDAOHelper().saveTranslateHistory(audioService.fromLanguage, audioService.toLanguage,
          audioService.indexPageFinalToLanguage.value, audioService.indexPageFinalToLanguage.value, audioService.taskId??'01010101010101',AppConst.TRANSLATOIN_TYPE_DIRECT,
      audioService.fromLanFlagDisplay.value,audioService.toLanFlagDisplay.value);
    }
  }

  void autoTTS() async {
    audioData =  Uint8List(0);
    print('autoPronounce.value:::${autoPronounce.value}');
    if (autoPronounce.value) { //如果自动播放按钮是打开的,则调用接口.
      initTTsWbSocket(DataCallBack(
        businessCallBack: (v) {
          autoSpeakWbSocket.send(json.encode(
              {
                'lang': audioService.toLanguage,
                'text': audioService.indexPageFinalToLanguage.value,
                'speed': voidSpeed.value/10,
                'male': voiceType.value == 1 ? true: false
              }
          ));
        }
      ));

    }
  }

  void initTTsWbSocket(DataCallBack callBack) async {
    stopTTSWs();
    autoSpeakWbSocket = ws.WebSocket (Uri.parse('wss://${NetWorkManager.WS_IP+NetWorkManager.TTS_REALTIME}'),
        headers: {
          'x-api-key': '264e03da4958e5ea405dd8f63b87da898757b821',
          // 'x-app-id': 'RquRazmzJpXLdp84'
        },
        timeout: Duration(seconds: 600));

    autoSpeakWbSocket.connection.listen((v) {
      print('autoSpeakWbSocket connection  status: ${v}');
    });


    autoSpeakWbSocket.messages.listen((v) async {
      print('autoSpeak WbSocket message from server : ${v}');
      if (v is List<dynamic>) {
        print('value length:  ${v.length}');
        audioData = CommonUtil.combineUint8Lists(audioData, v as Uint8List);

        return;
      }
      if (v == 'ok') return;
      Map result = json.decode(v.toString());
      if(result['action'] == 'started') {

        //发送心跳包.
        ttsWsTimer = Timer.periodic(Duration(seconds: 7), (timer) {
          if (autoSpeakWbSocket != null) {
            autoSpeakWbSocket.send('Heartbeat'); //
          }

        });

        callBack.businessCallBack!(v);

      } else if (result['action'] == 'synthesizing') {
         print('autoSpeakWbSocket =====> end: ${result['end']}');
         if (result['end']) {
           playAudioFromBytes(audioData);
           //播放完成后清空数据.
           audioData = Uint8List(0);
         }

      }

    });

    await autoSpeakWbSocket.connection.firstWhere((state) => state is ws.Connected);
  }

  void playAudioFromBytes(Uint8List data) async {
    player = AudioPlayer();
    // 将字节数据转换为 Uint8List
    await player?.play(BytesSource(data,mimeType: ''));
    stopTTSWs();
  }


  void stopTTSWs () {
    if (autoSpeakWbSocket != null) {
      autoSpeakWbSocket!.send(json.encode({
        'end': true
      }));
      autoSpeakWbSocket!.close();
      autoSpeakWbSocket = null;
    }
    autoSpeakWbSocket = null;
  }


  void stopAudioPlay() {
    player?.stop();
    stopTTSWs();
  }

  void showpoupWindowVoiceType (BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          width: Get.width,
          padding: EdgeInsets.all(20.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              InkWell(
                onTap: () {
                  voiceType.value = 1;
                  updateSettingData();
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: voiceType.value == 1 ? Text('男生',style: TextStyle(color: AppColors.app_base_theme_color),): Text('男生'),
                ),
              ),
              CommonWidgets.getMyDivider(),
              InkWell(
                onTap: () {
                  voiceType.value = 0;
                  updateSettingData();
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: voiceType.value == 0 ? Text('女生',style: TextStyle(color: AppColors.app_base_theme_color),): Text('女生'),
                ),
              )


            ],
          ),
        )),
        backgroundColor: Colors.white

    );
  }

  void showpoupWindowSpeed (BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          width: Get.width,
          padding: EdgeInsets.all(20.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              InkWell(
                onTap: () {
                  voidSpeed.value = 5;
                  updateSettingData();
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: voidSpeed.value == 5 ? Text('超慢',style: TextStyle(color: AppColors.app_base_theme_color),): Text('超慢'),
                ),
              ),
              CommonWidgets.getMyDivider(),
              InkWell(
                onTap: () {
                  voidSpeed.value = 10;
                  updateSettingData();
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: voidSpeed.value == 10 ? Text('正常',style: TextStyle(color: AppColors.app_base_theme_color),): Text('正常'),
                ),
              ),
              CommonWidgets.getMyDivider(),
              InkWell(
                onTap: () {
                  voidSpeed.value = 20;
                  updateSettingData();
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: voidSpeed.value == 20 ? Text('超快',style: TextStyle(color: AppColors.app_base_theme_color),): Text('超快'),
                ),
              )
              ,
            ],
          ),
        )),
        backgroundColor: Colors.white

    );
  }


  void chooseFromLanguages() async {
   final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
     'code': audioService.fromLanguage
   });
   audioService.fromLanguage = languageItem['code'];
   audioService.fromLanFlagDisplay.value = languageItem['desc'];

   changeLanguageReInitial();

  }

  void chooseToLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION,parameters: {
    'code': audioService.toLanguage
    });
    audioService.toLanguage = languageItem['code'];
    audioService.toLanFlagDisplay.value = languageItem['desc'];

    changeLanguageReInitial();
  }


  void changeLanguageReInitial() {
    if (audioService.isPlaying.value) {
      audioService.pauseRecorder();
      audioService.reInitWs();
      audioService.connectedWsAndRecorder('wss://${NetWorkManager.WS_IP + NetWorkManager.SPEECH_RECOGNITION}?channel=azure&transStrategy=2', DataCallBack(
        confirmCallBack: (v) {
            audioService.record();
        },
        businessCallBack: (m) {
          // 延迟到下一帧执行，确保布局完成
          SchedulerBinding.instance.addPostFrameCallback((_) {
            _autoScrollToBottom();
          });
        }
      ));
    }
  }


  void responseAudio() {
    if (_isCoolingDown) {
      return;
    };

    _isCoolingDown = true;

    if (audioService.isPlaying.value) {
      audioService.stopRecorderForIndex();
      saveTranslationRecords();

      if (allowOtherAppInput.value) {
        Clipboard.setData(ClipboardData(text: audioService.indexPageFinalToLanguage.value));
      }

      autoTTS();


    } else {
      initWsAndRecorder();
      // controller.audioService.stopRecorder();

    }

    _debounceTimer = Timer(Duration(milliseconds: 800), () {
      _isCoolingDown = false;
    });

  }

}